package net.jescort.web.servlet.controller.auth;

import net.jescort.repository.UserRepository;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 11-7-14
 * Time: 上午11:44
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping(value = {"/user/signup"})
public class SignupController
{
    private SignupValidator signupValidator = new SignupValidator();

    private UserRepository userRepository;

    @RequestMapping(method = RequestMethod.GET)
    public String showSignupForm(Model model, @ModelAttribute SignupFormBean formBean)
    {
        return "user/signup";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String showSignupForm(Model model, @ModelAttribute SignupFormBean formBean, BindingResult errors)
    {
        signupValidator.validate(formBean, errors);

        if (errors.hasErrors())
        {
            return showSignupForm(model, formBean);
        }

        // Create the user
        userRepository.createUser(formBean.getUsername(), formBean.getPassword(), formBean.getEmail());

        // Login the newly created user
        SecurityUtils.getSubject().login(new UsernamePasswordToken(formBean.getUsername(), formBean.getPassword()));

        return "redirect:/";
    }
}
